package com.itheima.controller;


import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.constant.TokenConstant;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import com.itheima.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Resource
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     *
     * @param
     * @return
     */
    @PostMapping("/sendMsg")
    //todo：如果用接口文档里给的电话id就会拿不到数据，即使用了Jason的转化格式也不行，TMD我也不知道为什么
    public R<String> sendMsg(@RequestBody User user) throws Exception {
        String phone = user.getPhone();
        //生成随机的4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("code={}", code);
        // todo:调用阿里云提供的短信服务API完成发送短信 ,什么都有，但是调用这个方法并不能真正发送短信，我还是不知道为什么，今天就搞了这俩半成品，我心态已经崩了
        SMSUtils.sendMessage(phone, code);
        redisTemplate.opsForValue().set(phone, code);
        System.out.println();
        return R.success("手机验证码短信发送成功");
    }


    /**
     * 移动端用户登录
     *
     * @return
     */
    @PostMapping("/login")
    public R<UserVo> login(@RequestBody Map map) {
        log.info(map.toString());

        //获取输入的手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //从redis获取保存的验证码
        String codeInRedis = (String) redisTemplate.opsForValue().get(phone);

        log.info("{}", "{}", "{}", phone, code, codeInRedis);
        //进行验证码的比对
        if (codeInRedis != null && codeInRedis.equals(code)) {

            //判断当前手机号对应的用户是否为新用户，新用户则自动注册---表user
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            String tokenString = String.valueOf(System.currentTimeMillis() + user.getId());
            String token = DigestUtils.md5DigestAsHex(tokenString.getBytes(StandardCharsets.UTF_8));
            log.info("userToken:{}", token);
            redisTemplate.opsForValue().set(TokenConstant.USER_TOKEN_PREFIX + token, JSON.toJSONString(user), 10, TimeUnit.MINUTES);
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            userVo.setToken(token);

            // 登录成功则移除缓存中的验证码
            redisTemplate.delete(phone);
            return R.success(userVo);
        }
        return R.error("登录失败");
    }



    /**
     * 登出
     * @param request
     * @return
     */
    //老子就是喜欢CV 真好不用一分钟
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request){
        String token =request.getHeader("AuthorizationUser");
        redisTemplate.delete(TokenConstant.USER_TOKEN_PREFIX+token);
        log.info("执行了登出功能");
        return  R.success("登出成功");
    }


}
